import request from '../../utils/request'
import { showSuccess, showError, showLoading, hideLoading } from '../../utils/util'

Page({
    data: {
        title: '',
        content: '',
        category: '',
        maxMembers: 5,
        location: '',
        latitude: null,
        longitude: null,
        startDate: '',
        startTime: '',
        endDate: '',
        endTime: '',
        tags: [],
        tagInput: '',
        canSubmit: false,
        loading: false,
        locating: false
    },

    onLoad() {
        // 设置默认时间为明天下午2点
        const tomorrow = new Date()
        tomorrow.setDate(tomorrow.getDate() + 1)

        this.setData({
            startDate: this.formatDate(tomorrow),
            startTime: '14:00',
            endDate: this.formatDate(tomorrow),
            endTime: '17:00'
        })
        this.checkSubmit()
    },

    onShow() {
        // 检查是否有从地图页面返回的位置信息
        const pages = getCurrentPages()
        const currentPage = pages[pages.length - 1]
        if (currentPage.data && currentPage.data.selectedLocation) {
            const { location, latitude, longitude } = currentPage.data.selectedLocation
            this.setData({
                location: location,
                latitude: latitude,
                longitude: longitude
            })
            this.checkSubmit()
        }
    },

    async onSubmit() {
        if (!this.data.canSubmit) {
            showError('请填写完整信息')
            return
        }

        // 验证时间
        if (!this.validateTime()) {
            return
        }

        if (this.data.loading) return

        this.setData({ loading: true })

        try {
            showLoading('发布中...')

            // 组合日期和时间
            const startDateTime = `${this.data.startDate} ${this.data.startTime}`
            const endDateTime = `${this.data.endDate} ${this.data.endTime}`

            const app = getApp()
            const postData = {
                title: this.data.title,
                content: this.data.content,
                category: this.data.category,
                maxMembers: this.data.maxMembers,
                location: this.data.location,
                latitude: this.data.latitude,
                longitude: this.data.longitude,
                startTime: startDateTime,
                endTime: endDateTime,
                tags: this.data.tags,
                authorId: app.globalData.userId,
                authorName: app.globalData.userInfo?.nickName || '用户'
            }

            console.log('提交的数据:', postData)

            const result = await request.post('/posts', postData)

            hideLoading()
            showSuccess('发布成功')

            setTimeout(() => {
                wx.redirectTo({
                    url: `/pages/post-detail/post-detail?id=${result.id}`
                })
            }, 1500)

        } catch (error) {
            hideLoading()
            this.setData({ loading: false })
            console.error('发布失败:', error)
            showError('发布失败，请重试')
        }
    },

    // 其他方法保持不变...
    onAutoLocation() {
        if (this.data.locating) return
        this.setData({ locating: true })
        wx.getLocation({
            type: 'gcj02',
            success: (res) => {
                const { latitude, longitude } = res
                this.reverseGeocode(latitude, longitude)
            },
            fail: (err) => {
                this.setData({ locating: false })
                console.error('获取位置失败:', err)
                if (err.errMsg.includes('auth deny') || err.errMsg.includes('auth denied')) {
                    this.showLocationAuthModal()
                } else {
                    showError('定位失败，请检查定位权限或手动输入地址')
                }
            }
        })
    },

    reverseGeocode(latitude, longitude) {
        const key = 'YOUR_MAP_KEY'
        const url = `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${key}`
        wx.request({
            url: url,
            success: (res) => {
                this.setData({ locating: false })
                if (res.data.status === 0) {
                    const address = res.data.result.address
                    const formattedAddress = res.data.result.formatted_addresses?.recommend || address
                    this.setData({
                        location: formattedAddress,
                        latitude: latitude,
                        longitude: longitude
                    })
                    this.checkSubmit()
                    showSuccess('定位成功')
                } else {
                    this.setData({
                        location: `位置(${latitude.toFixed(4)},${longitude.toFixed(4)})`,
                        latitude: latitude,
                        longitude: longitude
                    })
                    this.checkSubmit()
                    showSuccess('获取坐标成功')
                }
            },
            fail: (err) => {
                this.setData({ locating: false })
                this.setData({
                    location: `位置(${latitude.toFixed(4)},${longitude.toFixed(4)})`,
                    latitude: latitude,
                    longitude: longitude
                })
                this.checkSubmit()
                showSuccess('获取坐标成功')
            }
        })
    },

    showLocationAuthModal() {
        wx.showModal({
            title: '需要位置权限',
            content: '请在小程序设置中开启位置权限，以便自动获取您的位置信息',
            confirmText: '去设置',
            success: (res) => {
                if (res.confirm) {
                    wx.openSetting({
                        success: (settingRes) => {
                            if (settingRes.authSetting['scope.userLocation']) {
                                showSuccess('授权成功，请重新点击定位')
                            }
                        }
                    })
                }
            }
        })
    },

    onMapSelect() {
        wx.chooseLocation({
            success: (res) => {
                if (res.name && res.address) {
                    this.setData({
                        location: res.name,
                        latitude: res.latitude,
                        longitude: res.longitude
                    })
                    this.checkSubmit()
                    showSuccess('位置选择成功')
                }
            },
            fail: (err) => {
                console.error('选择位置失败:', err)
                if (err.errMsg.includes('auth deny')) {
                    this.showLocationAuthModal()
                } else {
                    showError('选择位置失败，请手动输入地址')
                }
            }
        })
    },

    onTitleInput(e) {
        this.setData({ title: e.detail.value })
        this.checkSubmit()
    },

    onContentInput(e) {
        this.setData({ content: e.detail.value })
        this.checkSubmit()
    },

    onCategorySelect(e) {
        this.setData({ category: e.currentTarget.dataset.category })
        this.checkSubmit()
    },

    onLocationInput(e) {
        this.setData({ location: e.detail.value })
        this.checkSubmit()
    },

    onStartDateChange(e) {
        this.setData({ startDate: e.detail.value })
        this.checkSubmit()
    },

    onStartTimeChange(e) {
        this.setData({ startTime: e.detail.value })
        this.checkSubmit()
    },

    onEndDateChange(e) {
        this.setData({ endDate: e.detail.value })
        this.checkSubmit()
    },

    onEndTimeChange(e) {
        this.setData({ endTime: e.detail.value })
        this.checkSubmit()
    },

    increaseMembers() {
        if (this.data.maxMembers < 20) {
            this.setData({ maxMembers: this.data.maxMembers + 1 })
        }
    },

    decreaseMembers() {
        if (this.data.maxMembers > 1) {
            this.setData({ maxMembers: this.data.maxMembers - 1 })
        }
    },

    onTagInput(e) {
        this.setData({ tagInput: e.detail.value })
    },

    addTag() {
        const tag = this.data.tagInput.trim()
        if (!tag) {
            showError('请输入标签内容')
            return
        }
        if (tag.length > 10) {
            showError('标签不能超过10个字')
            return
        }
        if (this.data.tags.length >= 5) {
            showError('最多只能添加5个标签')
            return
        }
        if (this.data.tags.includes(tag)) {
            showError('标签已存在')
            return
        }
        const tags = [...this.data.tags, tag]
        this.setData({
            tags: tags,
            tagInput: ''
        })
    },

    removeTag(e) {
        const index = e.currentTarget.dataset.index
        const tags = [...this.data.tags]
        tags.splice(index, 1)
        this.setData({ tags: tags })
    },

    checkSubmit() {
        const { title, content, category, location, startDate, startTime, endDate, endTime } = this.data
        const canSubmit = title && content && category && location && startDate && startTime && endDate && endTime
        this.setData({ canSubmit })
    },

    formatDate(date) {
        const year = date.getFullYear()
        const month = (date.getMonth() + 1).toString().padStart(2, '0')
        const day = date.getDate().toString().padStart(2, '0')
        return `${year}-${month}-${day}`
    },

    validateTime() {
        const { startDate, startTime, endDate, endTime } = this.data
        const startDateTime = new Date(`${startDate} ${startTime}`)
        const endDateTime = new Date(`${endDate} ${endTime}`)
        if (endDateTime <= startDateTime) {
            showError('结束时间必须晚于开始时间')
            return false
        }
        const now = new Date()
        if (startDateTime <= now) {
            showError('开始时间必须在当前时间之后')
            return false
        }
        return true
    },

    onCancel() {
        wx.showModal({
            title: '确认取消',
            content: '确定要取消发布吗？已填写的内容将不会被保存',
            success: (res) => {
                if (res.confirm) {
                    wx.navigateBack()
                }
            }
        })
    }
})